// OpentTxl-C Version 11 safe precise time stamps
// J.R. Cordy, May 2024

// Copyright 2024, James R. Cordy and others

// Permission is hereby granted, free of charge, to any person obtaining a copy of this software 
// and associated documentation files (the “Software”), to deal in the Software without restriction, 
// including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, 
// and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, 
// subject to the following conditions:

// The above copyright notice and this permission notice shall be included in all copies 
// or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE 
// AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

// C standard includes
#include <stdlib.h>
#include <stdio.h>
#ifdef WIN
    #include <windows.h>
#else
    #include <time.h>
    #include <sys/time.h>
#endif

// Uses safe strings
#include "strings.h"

// Check interface consistency
#include "time.h"

// Avoid dynamic allocation
#define MAXTIMEWIDTH 128
static string time_buffer; 

char * time_precisetime()
{
    #ifdef WIN
        FILETIME stp;
        SYSTEMTIME st,lt;
        TIME_ZONE_INFORMATION tz;
        GetSystemTimePreciseAsFileTime(&stp);
        FileTimeToSystemTime(&stp,&st);
        GetTimeZoneInformation(&tz);
        SystemTimeToTzSpecificLocalTime(&tz,&st,&lt);

        stringprintf(time_buffer, "%02d-%02d-%02d-%02d:%02d:%02d.%03d",
            lt.wYear, lt.wMonth, lt.wDay, lt.wHour, lt.wMinute, lt.wSecond, lt.wMilliseconds);
    #else
        struct timeval curTime;
        gettimeofday(&curTime, NULL);
        int milli = curTime.tv_usec / 1000;

        char buffer [MAXTIMEWIDTH];
        strftime(buffer, 80, "%Y-%m-%d %H:%M:%S", localtime(&curTime.tv_sec));

        time_buffer[0] = '\0';
        stringprintf(time_buffer, "%s.%03d", buffer, milli);
    #endif

    return (char *) time_buffer;
}
